<?php

namespace xyb2b;

use catchAdmin\api\model\Order;
use catchAdmin\customs\model\HnOrderDetail;
use catchAdmin\externalGoods\model\MessageQueue;
use catchAdmin\externalGoods\model\NewNotify;
use catchAdmin\externalGoods\model\TenantGoods;
use catchAdmin\externalGoods\service\GoodsService;
use catchAdmin\externalGoods\model\Notify as externalNotify;
//use catcher\base\CatchRequest as Request;
use catchAdmin\externalGoods\service\OrderLogisticsTrackService;
use catchAdmin\externalGoods\service\OrderService;
use catchAdmin\externalGoods\service\XyGoodsService;
use houniao\api\v1\Goods;
use think\facade\Db;
use think\Request;
use catcher\CatchResponse;
use houniao\tools\Params;
use think\Exception;
use think\facade\Log;

class Notify
{
//    protected $app_key = '2f5bb2157a9f810d';
//    protected $secret='b37682554865a6deb1cc347b0b9ec7da';
    protected $app_key = '62ae4e5e226a972c';
    protected $secret='2b7db6bdb6cc689de3cda48a4fe80095';

    const GOODS_ADD = 'goods.add';//商品新增
    const GOODS_UPD = 'goods.update';//商品更新
    const GOODS_SHELVE = 'goods.shelve';//商品上架
    const GOODS_UNSHELVE = 'goods.unshelve';//商品下架
    const GOODS_PRICE = 'goods.price';//商品价格库存
    const GOODS_STOCK = 'goods.stock';//商品库存
    const ORDER_SEND = 'order.send';//订单发货
    const ORDER_STATUS = 'order.status';//订单状态更新
//    const AFTER_SALE_STATUS = 'after.sale.status';//售后处理更新
    const ORDER_TRACK = 'track.info';//物流通知

    public function notify(Request $request){
        $data = $request->param();
        $data['result_content'] = json_decode($data['result_content'],true);


        /***
        $data = '{
  "notice_code": "GENERATE_ORDER_NOTICE_V2",
  "sign": "beeecf44eaa042c7705b48ff41e654bf",
  "result_content": "{\"is_success\":1,\"merchant_order_id\":\"AAAAAAAORDER1666861733068\",\"order_freight_amount\":\"5.00\",\"order_id\":\"OP1000000088420\",\"order_list\":[{\"child_order_id\":\"O1000000148979\",\"freight_amount\":\"5.00\",\"order_status\":1001,\"pay_amount\":\"525.99\",\"sku_list\":[{\"batch_id\":\"CGRK202206072002-20240409-00000007\",\"buy_num\":1,\"package_num\":1,\"price_type\":0,\"sku_code\":\"174171-K\",\"sku_id\":174171,\"sku_pay_amount\":\"520.99\",\"sku_price\":\"500.00\",\"sku_tax_amount\":\"20.99\",\"sku_tax_difference\":\"0\",\"sku_tax_rate\":\"0.0630\"}],\"tax_amount\":\"20.99\",\"tax_difference\":\"0\"}],\"order_pay_amount\":\"525.99\",\"order_tax_amount\":\"20.99\",\"order_tax_difference\":\"0\",\"platform_discount_amount\":\"0\",\"shop_discount_amount\":\"0\"}",
  "merchant_id": "2022102529034561",
  "ret_msg": "处理成功",
  "business_id": "e098ee8e-efff-4f86-9771-543ac0b38224",
  "ret_code": "200",
  "sign_type": "MD5",
  "version": "2"
}';

        $data = json_decode($data, true);

         **/

        //订单生成
//        $data = '{"notice_code":"generate_order_notice_v2","sign":"f1e675702fb145ccb0c3ed4193cd1fb4","result_content":{"error_sku_list":[],"generate_fail_type":2,"is_success":2,"merchant_order_id":"1232341235533_1","order_id":"Z7333109230061589"},"merchant_id":"2024112997124650","ret_msg":"库存不足","business_id":"1f4fe0a4-9993-4cee-b77e-d4651e2a9a7f","ret_code":"301018","sign_type":"MD5","version":"2"}';
//        $data = '{"notice_code":"generate_order_notice_v2","sign":"9ca482deb1c5a28ab81a25a9ecf9286d","result_content":{"error_sku_list":[],"generate_fail_type":2,"is_success":2,"merchant_order_id":"1232341235533_1","order_id":"Z7334659771968343"},"merchant_id":"2024112997124650","ret_msg":"库存不足","business_id":"56aaf7f6-b753-4829-b501-4003f835d67c","ret_code":"301018","sign_type":"MD5","version":"2"}';

//        $data = '{"notice_code":"generate_order_notice_v2","sign":"ef170386b069c4786ecd2a71427c09d6","result_content":{"is_success":1,"merchant_order_id":"412432332412335533_1","order_freight_amount":"7.50","order_id":"OP1000002680612","order_list":[{"child_order_id":"O1000002810850","freight_amount":"7.50","order_status":1001,"pay_amount":"62.43","sku_list":[{"batch_id":"QTRK202308082012-20251016-00000007","buy_num":1,"package_num":1,"price_type":1,"sku_code":"632613-K","sku_id":632613,"sku_pay_amount":"54.93","sku_price":"45.20","sku_tax_amount":"9.73","sku_tax_difference":"0","sku_tax_rate":"0.1000"}],"tax_amount":"9.73","tax_difference":"0"}],"order_pay_amount":"62.43","order_tax_amount":"9.73","order_tax_difference":"0","platform_discount_amount":"0","shop_discount_amount":"0"},"merchant_id":"2024112997124650","ret_msg":"处理成功","business_id":"a748793d-f04c-4bf9-9842-11459966e292","ret_code":"200","sign_type":"MD5","version":"2"}';
//        $data = json_decode($data, true);

        //如果是 文档中复制过来的需要处理
//        $data['result_content'] = json_decode($data['result_content'],true);

        //dd($data);

        $redis = new \Redis();
        $redis->connect('127.0.0.1',6379);
//        $redis->select(14);
        $redis->auth(config('cache.stores.redis.password'));
//        $redis->auth('QiAoYi1234.5678.');

        $unique_id = $data['sign'];
        $cache_key = "cross_xy_notify_request:" . $unique_id;
        // 请求去重

        //dd($redis->exists($cache_key));

        if ($redis->exists($cache_key)) {
            die(json_encode([
                'success'=> 'true',
                'message'=> '接收成功'
            ],JSON_UNESCAPED_UNICODE));
        }
        $redis->setex($cache_key, 5, 'processing'); // 缓存 5 秒

        // 将有效请求推送到队列
        //$redis->lpush('cross_xy_notify_queue', json_encode($data,JSON_UNESCAPED_UNICODE));

        //记录日志
        $notifyData = [
            'type'=>$data['notice_code'],
//            'type_name'=>$msg,
            'type_name'=>'',
            'status'=> 1 ,//success,
            'notify_data'=>json_encode($data,JSON_UNESCAPED_UNICODE),
            'remark'=>'',
            'sign'=>$data['sign'],
            'supplier_id'=>3
        ];
        $notifyModel = new externalNotify();
        $notifyModel->save($notifyData);

// **直接处理当前请求**
        try {
            // 实际处理逻辑
            $result_content = $data;
            $xyGooodsService = new XyGoodsService;
            $ddddata = $xyGooodsService->{$data['notice_code']}($result_content);

            if ($ddddata['status'] == 1) {
                die(json_encode([
                    'success' => 'true',
                    'message' => '接收成功'
                ], JSON_UNESCAPED_UNICODE));
            } else {
                throw new Exception($ddddata['msg']);
            }
        } catch (\Exception $exception) {
            // 处理失败，记录日志或其他操作
//            dd($exception->getMessage());
            die(json_encode([
                'success' => 'false',
                'message' => '处理失败: ' . $exception->getMessage()
            ], JSON_UNESCAPED_UNICODE));
        }

        // **将其他并发请求推送到队列**
//        $redis->lpush('cross_xy_notify_queue', json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    //检验sign
    public function checkSign($data,$request_sign)
    {
        $data['app_key'] = $this->app_key;

        $data =  Params::paraFilter($data);

        //对待签名参数数组排序
        $old = $data;
        $data = Params::argSort($data);

        //生成签名结果
        $makeSign = Params::buildRequestMysign($data,$this->secret);

        if ($makeSign == $request_sign) {
            return true;
        } else {
            return false;
        }
    }

    //添加消息
    public function addMessage($message,$retries=0,$tenant_id = null,$priority=0){
        unset($message['sign']);
        $messageQueue = new MessageQueue;

        $data = [];
        //拿到所有商户数据，后期重新搞
        $list = [
            ['tenant_id'=>'10043','notify_url'=>'http://cross.qekj.net'],
            ['tenant_id'=>'10050','notify_url'=>'https://gateway.jsbcmall.com/app/callback/ltMessage'],
            ['tenant_id'=>'10143','notify_url'=>'http://cross.qekj.net/callback/SyncShop'],
//            ['tenant_id'=>'10144','notify_url'=>'http://cross.qekj.net/callback/SyncShop1110'],
            ['tenant_id'=>'10146','notify_url'=>'http://testpssnotify.indoorbuy.com/Notify/index/userType/shoplongtan/messageType/OrderExpress'],
            ['tenant_id'=>'10147','notify_url'=>'http://cross.qekj.net/callback/SyncShop1116'],
            ['tenant_id'=>'10161','notify_url'=>'http://cross.qekj.net/callback/SyncShop1122'],
        ];

        //商品类型通知
        if(array_key_exists('data',$message) && array_key_exists('goods_spu',$message['data'])){
            foreach ($list as $key => $value){
                //判断小池子是否选择了商品
                $find = (new TenantGoods())->where([
                    'tenant_id'=>$value['tenant_id'],
                    'goods_spu'=>$message['data']['goods_spu']
                ])->find();
                if(!$find) {
                    unset($list[$key]);
                }
            }
        }

        //只发送给对应商户
        if(null !== $tenant_id){
            $new_list = array_column($list,null,'tenant_id');
            $list = [$new_list[$tenant_id]];
        }

        foreach ($list as $value){
            $message['sign'] = $this->_makeSign($message);
            $message['request_url'] = $value['notify_url'];
            $data[] = [
                'message'=>$message,
                'retries'=>$retries,
                'priority'=>$priority,
                'to_tenant_id'=>$value['tenant_id']
            ];
        }

        $result =  $messageQueue->saveAll($data);
        if(!$result){
            throw new Exception('消息添加失败');
        }
    }

    protected function _makeSign($data){

        return md5(stripslashes(json_encode($data,JSON_UNESCAPED_UNICODE)));
    }

    //人脸机器，设备代码
    public function getDeviceCode($id,Request $request){
        $device_id = $id;

        $arr = [
            '1e843749d1127b9a' => '35CX-7WPC-LJAL-RPVN',
//            '43741452ab8426f4' => 'VDVU-AUCX-NVTS-RSZX',
            '43741452ab8426f4' => 'TXD6-YLQT-XV8E-8GCW',
            '8662bb7c865f6314' => '8HDJ-YSXE-CV99-BDRL',
            '84c5a69307bb471' => 'FTMP-HMD7-RXYX-GZFW',
            '7b3f5c3f2aac1721' => 'CFZX-FNP9-6G6Q-TXAN',
            '1d6c6c7c4aa7c736'=> 'J7X8-G5LR-6DXZ-CGWX',
            'c421a82d8b894df7'=> '5DEH-EWGC-HASA-USPN',
            '67c79ff5f77faaf1'=> 'X9J8-PHXS-XPXC-XXXF',
            '6809ccd6871f1cb0'=> 'F89T-GHXG-RAEJ-HHX2',
            '2a1e9cfd3f169eef'=> 'XGDY-7NXY-HMJK-UXLN',
            'eb14335a95d40de4'=> 'VJE8-BGKL-LXJR-XRXB',
            'cf9d795e8253bd70'=> '3BG2-TXP9-BKVP-XNPX',
            '78oe7dd5967b506b'=> '7GTG-FNQP-N5XX-DBYX',
            '6T6Da82440a191d'=> '5K5V-XPLX-QWX3-UL7X',
            '253683360b152d50'=> 'AJVM-RJFF-VCPX-AUGB',
            '78ce7dd5967b506b'=> 'VVW5-XXP7-38CH-ZNCC',
            '6ff6ba8244baf9fd'=> 'VXFX-ASFL-HH44-AC8N',
            '1f53bddcff28f148'=> 'MQRE-LXMB-RBLC-SF52',
            '7c1099425700557'=> 'KNFE-Z6XN-6XCQ-AXDN'
        ];

        if(array_key_exists($device_id,$arr)){
            return CatchResponse::success($arr[$device_id],'授权码获取成功');
        }else{
            return CatchResponse::fail('设备ID不存在！');
        }
    }
}